var fs = require('fs');
var path = require('path');
var Canvas = require('canvas');
// 饼图需要自定义的参数
var pieArgument = {
  canvasWidth: 210,
  canvasHeight: 128,
  sum: 3456,
  item: 1234,
  fillColor: "#3ebbc1",
  bgColor: '#e6e6e6',
  fontColor: '#3ebbc1'
};
// 饼图 方法定义
function pie (pieArgument) {
  var percent = pieArgument.item/pieArgument.sum;
  var pieLable = (percent * 100).toString().substring(0,5);
  if ((percent * 100).toString().substring(5, 6) >= 5) {
    var aa = (Number(pieLable.substring(4,5)) + 1).toString();
    var bb = pieLable.split('');
    bb.splice(4,1,aa);
    pieLable = bb.join('') + '%';
  } else {
    pieLable = pieLable * 100 + '%';
  }
  var radian = Math.PI/180*360*percent - Math.PI*0.5;
  var canvas = new Canvas(pieArgument.canvasWidth, pieArgument.canvasHeight);
  var ctx = canvas.getContext('2d');
  ctx.beginPath();
  ctx.translate(pieArgument.canvasHeight/2,pieArgument.canvasHeight/2);//定义中心点
  ctx.moveTo(0,0);
  ctx.arc(0,0,pieArgument.canvasHeight/2,0,Math.PI*2,false);
  ctx.fillStyle=pieArgument.bgColor;
  ctx.fill();
  ctx.moveTo(0,0);
  ctx.arc(0,0,pieArgument.canvasHeight/2,Math.PI*1.5,radian,true);
  ctx.fillStyle=pieArgument.fillColor;
  ctx.fill();

  ctx.translate(pieArgument.canvasWidth/2,0);//定义中心点
  ctx.font = '20px 苹方-简';
  ctx.textAlign = "center";
  ctx.textBaseline = 'middle';
  ctx.fillStyle=pieArgument.fontColor;
  ctx.fillText(pieLable, 0,0);

  ctx.closePath();
  console.log(canvas.toDataURL());//生成图片base64
  canvas.createPNGStream().pipe(fs.createWriteStream(path.join(__dirname, 'pie.png'))) // 生成本地图片(指定文件名)
}
pie(pieArgument);